package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strconv"
	"sync"
	"time"
)

func main() {
	personCount := 5
	useChannel(personCount)
}

func useChannel(personCount int) {
	baseFateRate := Rands(0.0, 0.4) //基础体脂率
	chanPerson := make(chan *Person, personCount)
	wg := sync.WaitGroup{}
	wg.Add(personCount)
	for i := 0; i < personCount; i++ {
		go func(num int) {
			defer wg.Done()
			name := "user_channel_No_" + strconv.Itoa(num)
			fatRateUpdate := Rands(baseFateRate-0.2, baseFateRate+0.2)
			p := &Person{}
			p.register(name, fatRateUpdate)
			pf := &PersonFormat{
				Name:    name,
				FatRate: fatRateUpdate,
			}
			data, err := json.Marshal(pf)
			if err != nil {
				fmt.Println("marshal 出错：", err)
			}
			if str, err := os.Getwd(); err == nil {
				path := str
				if err := p.saveInfoByJsonFile(data, path+"/homework/five/person.json"); err != nil {
					log.Println("写入文件出错：", err)
				}
			} else {
				log.Fatal("获取当前路径出错")
			}
			chanPerson <- p
		}(i)
	}
	wg.Wait()
	close(chanPerson)
	maps := updateFatRate(chanPerson, personCount)
	for i := 0; i < personCount; i++ {
		go func(num int) {
			name := "user_channel_No_" + strconv.Itoa(num)
			if personInfo, ok := maps.Load(name); ok {
				personInfo := personInfo.(List)
				fmt.Println(name, "当前排名第：", personInfo.index, "其体脂率为:", personInfo.fateRate)
			}
		}(i)
	}
	time.Sleep(2 * time.Second)
}

func updateFatRate(ch chan *Person, personCount int) (m sync.Map) {
	m = sync.Map{}
	persons := Persons{}
	for person := range ch {
		persons = append(persons, person)
	}
	//冒泡排序
	BubbleSort(persons)
	//快排
	//QuickSort(persons, 0, personCount-1)
	for ind, person := range persons {
		personInfoMap := List{
			index:    ind,
			name:     person.name,
			fateRate: person.fateRate,
		}
		m.Store(person.name, personInfoMap)
	}
	return
}
